import 'package:eyepetizer_example/config/string.dart';
import 'package:eyepetizer_example/page/discovery_page.dart';
import 'package:eyepetizer_example/page/home_page.dart';
import 'package:eyepetizer_example/page/hot_page.dart';
import 'package:eyepetizer_example/page/mine_page.dart';
import 'package:eyepetizer_example/utils/toast_util.dart';
import 'package:flutter/material.dart';

class TabNavigation extends StatefulWidget {
  const TabNavigation({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TabNavigationState();
  }
}

class _TabNavigationState extends State<StatefulWidget> {
  PageController pageController = PageController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: _onWillPop,
        child: Scaffold(
            body: PageView(
              controller: pageController,
              physics: const NeverScrollableScrollPhysics(),
              children: const [
                HomePage(),
                DiscoveryPage(),
                HotPage(),
                MinePage(),
              ],
            ),
            bottomNavigationBar: getBottomNavigationBar()));
  }

  BottomNavigationBar getBottomNavigationBar() => BottomNavigationBar(
        currentIndex: currentIndex,
        selectedItemColor: const Color(0xff000000),
        unselectedItemColor: const Color(0xff9a9a9a),
        type: BottomNavigationBarType.fixed,
        items: [
          tabItem(AppString.home, "images/ic_home_normal.png",
              "images/ic_home_selected.png"),
          tabItem(AppString.discovery, "images/ic_discovery_normal.png",
              "images/ic_discovery_selected.png"),
          tabItem(AppString.hot, "images/ic_hot_normal.png",
              "images/ic_hot_selected.png"),
          tabItem(AppString.mine, "images/ic_mine_normal.png",
              "images/ic_mine_selected.png"),
        ],
        onTap: (index) {
          currentIndex = index;
          pageController.jumpToPage(currentIndex);
          setState(() {});
        },
      );

  int currentIndex = 0;

  BottomNavigationBarItem tabItem(
          String title, String normalIcon, String activeIcon) =>
      BottomNavigationBarItem(
          icon: Image.asset(
            normalIcon,
            width: 24,
            height: 24,
          ),
          activeIcon: Image.asset(
            activeIcon,
            width: 24,
            height: 24,
          ),
          label: title);

  DateTime? lastTime;

  Future<bool> _onWillPop() async {
    if (lastTime == null ||
        DateTime.now().difference(lastTime!) > const Duration(seconds: 2)) {
      lastTime = DateTime.now();
      AppToast.showTip(AppString.exit_tip);
      return false;
    } else {
      // 自动出栈
      return true;
    }
  }
}
